package com.ruoyi.oauth.sso.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.oauth.domain.OauthToken;
import com.ruoyi.oauth.utils.OAuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class OauthLoginService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private UserDetailsService userDetailsService;
    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 判断是否登录
     * @return
     */
    public boolean checkLogin(HttpServletRequest request){
        try{
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser))
            {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 验证登录
     * @param request
     * @return
     */
    public String login(HttpServletRequest request){
        String username = request.getParameter(OAuthUtil.OAUTH_USERNAME);
        String password = request.getParameter(OAuthUtil.OAUTH_PASSWORD);
        String code = request.getParameter("code");
        String uuid = request.getParameter("uuid");

        // 验证码校验
        loginService.validateCaptcha(username, code, uuid);

        return login(username, password);
    }

    /**
     * 验证登录
     * @param username
     * @param password
     * @return
     */
    public String login(String username, String password){
        // 登录前置校验
        loginService.loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(ServletUtils.getRequest()));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        loginService.recordLoginInfo(loginUser.getUserId());
        return tokenService.createToken(loginUser);
    }

    /**
     * 登录验证
     *
     * @param user 用户详细
     * @return 结果
     */
    public String login(SysUser user)
    {
        UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUserName());
        // 用户验证
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(userDetails.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        return tokenService.createToken((LoginUser)userDetails);
    }

    /**
     * 登录验证
     *
     * @param user 用户详细
     * @return 结果
     */
    public String login(UserDetails user)
    {
        // 用户验证
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        return tokenService.createToken((LoginUser)user);
    }

    public void logout(OauthToken token){
        tokenService.delLoginUser(token.getAccessToken());
        redisCache.deleteObject("oauth_refresh:"+ token.getRefreshToken());
        redisCache.deleteObject("oauth_token:"+ token.getAccessToken());
    }

    public String createToken(LoginUser user){
        return tokenService.createToken(user);
    }
}
